<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Mabang
{

    public $max_id = null;

    public $locationsku = null;

    public $status = " B.STATUS = '已完成' ";

    public function __construct()
    {
        $this->CI =& get_instance();
        $this->db1 = $this->CI->load->database('default', TRUE);
        $this->db2 = $this->CI->load->database('oracle', TRUE);
		$this->CI->load->model('Function_m','fun');
    }

    public function get_db1()
    {
        $query = $this->db1->query("SELECT * FROM db1 where date='$date'");
        return $query->row_array();
    }

    public function get_db2()
    {
        $query = $this->db2->query("SELECT * FROM db2 where date='$date'");
        return $query->row_array();
    }

    public function getskuname($skuname, $field = "*")
    {
        $sql = "SELECT $field FROM DB_PRODUCT WHERE SEQUENCEID='" . $skuname . "' ";
        $res = $this->db2->query($sql);
        $depts = $res->result();
        if ($depts) {
            return $depts;
        } else {
            return 200;
        }
    }
	  public function getskunamelike($skuname, $field = "*")
    {
        $sql = "SELECT $field FROM DB_PRODUCT WHERE SEQUENCEID like '%" . $skuname . "%' ";
        $res = $this->db2->query($sql);
        $depts = $res->result();
        if ($depts) {
            return $depts;
        } else {
            return 200;
        }
    }

	 public function getsellprice($orderID, $field = "*")
    {
        $sql = "SELECT $field FROM DB_SELL WHERE ORDERID='" . $orderID . "' AND FLAG !=3";
        $res = $this->db2->query($sql);
        $depts = $res->result();
        if ($depts) {
          $price =0;
		  foreach($depts as $key=>$rs)
			{
			$price = $price+($rs->ORDERNUM * $rs->SELLPRICE);

		
		  }
		  	return $price;
        } else {
            return 200;
        }
    }

	public function getorderdata($orderID, $field = "*"){

		$sql = "SELECT $field FROM DB_ORDER WHERE TRADEID='" . $orderID . "'";
        $res = $this->db2->query($sql);
        $depts = $res->result();
        $deptsname = $this->object2array($depts);
		if($deptsname){
			return $deptsname[0];
		}else{
			return false;
		}
	}

    public function getshopname($where = "")
    {
        $sql = "select SID,NAME,EMAIL,RESERVE12,OPER from DB_SHOP where $where OPENFLAG = 1";

        $res = $this->db2->query($sql);
        $depts = $res->result();

        foreach ($depts as $key => $rs) {
            $deptsname[$rs->RESERVE12][] = $rs;
        }
        $deptsname = $this->object2array($deptsname);
        return $deptsname;
    }

	//判断订单是否存在在马帮。如果存在。新系统做废
	public function checkmabangOrder()
	{
		$dates = date("Y-m-d",time()-10*86400);

		$datesstime = date("Y-m-d",time()-86400);
		$startime = $dates . " 00:00:00";
        $endtime = date("Y-m-d H:i:s");
		 $resorder = $this->db1->get_where("db_order_list"," dates>='".$datesstime."' ")->result_array();
		echo count($resorder);
		 
		if(count($resorder)>0)
		{
			foreach($resorder as $key=>$rs)
			{
				$order_sn = $rs["tradeid"];
				$shopname = $rs["shopname"];

				$orderdata = $this->db2->get_where('DB_ORDER',"TRADEID='".$order_sn."'  AND ( STATUS !='作废') AND STATUS !='新订单'  AND to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')>='" . $startime . "' and to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='" . $endtime . "'  ")->result_array();
			
				if($orderdata[0]["ORDERID"])
				{
					//两边都存在的订单。将马帮的作废
						$this->db2->query("UPDATE DB_ORDER SET STATUS='作废',BANSENDFLAG=1 where ORDERID='".$orderdata[0]["ORDERID"]."'");
						/*
						$post="";
						$post["order_status"] = 6;
						$this->db1->update("db_order_list",$post," order_id='".$rs["order_id"]."'");
						$imgdata="";
						$imgdata["content"] = '与马帮订单重复！修改状态为：作废';
						$imgdata["goods_id"] = $rs['order_id'];	//订单ID db_order_list
						$imgdata["updatetime"] = date("Y-m-d H:i:s");
						$imgdata["createUid"] = 0;
						$imgdata["types"] = 3;
						$imgdata["createUser"] ='auto';
						$this->db1->insert('db_goods_log', $imgdata);*/
				}
			}
			 
		}
		 
	}

	public function checkmabangOrderduboo()
	{
		$dates = date("Y-m-d",time()-20*86400);
		$startime = $dates . " 00:00:00";
        $endtime = date("Y-m-d H:i:s");
		$resorder = $this->db1->get_where("db_order_list"," ( order_status !=6) AND saleschannel = 'Aliexpress' ")->result_array();
		if(count($resorder)>0)
		{
			foreach($resorder as $key=>$rs)
			{
				$order_sn = $rs["tradeid"];
				$shopname = $rs["shopname"];
				$orderdata = $this->db2->get_where('DB_ORDER',"TRADEID='".$order_sn."' AND SHOPTYPE='".$shopname."' AND ( STATUS !='作废') AND  STATUS !='新订单'  AND to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')>='" . $startime . "' and to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='" . $endtime . "'  ")->result_array();

				if($orderdata[0]["ORDERID"])
				{
					echo $orderdata[0]['ORDERID'];
					echo "<br>";
				}
			}
		}
	}

    public function getshopOrder($s, $e, $shopdata)
    {
        if (count($shopdata) == 0) {
            die('未选中店铺！');
        }

        $startime = $s . " 00:00:00";
        $endtime = $e . " 23:59:59";
        $listdb = array();
        foreach ($shopdata as $shopid) {
            //$sql = "select NAME from DB_SHOP where SID ='".$shopid."' AND  OPENFLAG = 1";
            //$res = $this->db2->query($sql);
            //$depts = $res->result();
            //$shopname = $depts[0]->NAME;
            //print_r($shop);
            //die;
            // MONEYASK + MONEYEXPRESSASK  商品+运费 = 客人付款金额
            //FINALVALUEFEE 平台费用
            //SKU QLRESERVE2
            //SELLNUM 订单SKU数
            // ORDERID 订单ID ， SHOPTYPE店铺名，SHOPTYPEID 店铺ID，MONEYASK 订单售价，MONEYACTION 合计商品成本，MONEYASK 商品金额，MONEYEXPRESSASK 运费收入，MONEYEXPRESSACTION真实运费，SLRESERVE7 预估运费 ， PAYPALFEEAMOUNT交易费用，ORDERNUM订单商品数
            //$sql = "select ORDERID,SHOPTYPE,SHOPTYPEID,MONEYASK,MONEYACTION,MONEYEXPRESSASK,MONEYEXPRESSACTION,SLRESERVE7,PAYPALFEEAMOUNT,SELLNUM,FINALVALUEFEE,QLRESERVE2 from DB_ORDER where SHOPTYPEID = '".$shopid."'  AND STATUS = '已完成'  AND to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')>='".$startime."' and to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='".$endtime."'";
            $sql = "select ORDERID,SHOPTYPE,SHOPTYPEID,MONEYASK,MONEYACTION,MONEYEXPRESSASK,MONEYEXPRESSACTION,SLRESERVE7,PAYPALFEEAMOUNT,SELLNUM,FINALVALUEFEE,QLRESERVE2 from DB_ORDER where SHOPTYPE = '" . $shopid . "'  AND STATUS = '已完成'  AND to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')>='" . $startime . "' and to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='" . $endtime . "' order by MONEYACTION ASC";


            $query = $this->db2->query($sql);
            $res = $query->result();
            $res = $this->object2array($res);
            if (count($res) > 0) {
                foreach ($res as $key => $rs) {
                    $allmount = $rs['MONEYASK'] + $rs['MONEYEXPRESSASK'];    //商品售价等于商品销售价+运费
                    $res[$key]["allmount"] = $allmount;
                    if ($rs["MONEYEXPRESSACTION"]) {
                        $freight = $rs["MONEYEXPRESSACTION"];    //真实运费
                    } else {
                        $freight = 0;            //预估运费
                    }
                    $res[$key]["freight"] = $freight;
                    //商品成本等于本次成本
                    $res[$key]["Costofgoods"] = $rs["MONEYACTION"];
                    $lastprice = $allmount - $freight - $rs["MONEYACTION"] - $rs["PAYPALFEEAMOUNT"] - $rs["FINALVALUEFEE"];    //总金额-运费-成本-交易费-平台使用费
                    $res[$key]["lastprice"] = $lastprice;
                }
                $listdb[$shopid] = $res;
            }
        }


        return $listdb;
    }

	public function getskusell($goods,$startime,$endtime)
	{
			$allnum = 0;
			$time = strtotime($startime);
			$startime = date("Y-m-d",$time)." 00:00:00";
			$endtime = strtotime($endtime);
			$endtime = date("Y-m-d",$endtime)." 23:59:00";
			ini_set('max_execution_time', '0');
			$newarray =array();
			$sql = "select ORDERID from DB_ORDER where STATUS = '已完成' AND QLRESERVE2 LIKE ',".trim($goods).",'  AND to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')>='2016-10-01 00:00:00' and to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='2016-10-31 23:59:59' order by MONEYACTION ASC";
			
			$query = $this->db2->query($sql);
			$res = $query->result();
			$res = $this->object2array($res);
			 foreach ($res as $key => $rs) {
				 $this->db2->select('PRODUCTID, ORDERNUM, PRODUCTNAME');
				$sell =$this->db2->get_where('DB_SELL',"ORDERID='".trim($rs["ORDERID"])."' and FLAG != 3")->result_array();
				if(count($sell)>0)
				 {
					foreach($sell as $kye=>$se)
					 {
						$allnum = $allnum+$se["ORDERNUM"];
					 }
				}
			 }
			return $allnum;
	
	}
	
	/****导出某个时间段内所有SKU的销售*****/
	public function getselltop200()
	{
		ini_set('max_execution_time', '0');
		$newarray =array();
		$sql = "select ORDERID from DB_ORDER where STATUS = '已完成'  AND to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')>='2016-10-01 00:00:00' and to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='2016-10-31 23:59:59' order by MONEYACTION ASC";
		$query = $this->db2->query($sql);
		$res = $query->result();
		$res = $this->object2array($res);
		 foreach ($res as $key => $rs) {
			 $this->db2->select('PRODUCTID, ORDERNUM, PRODUCTNAME');
			$sell =$this->db2->get_where('DB_SELL',"ORDERID='".trim($rs["ORDERID"])."' and FLAG != 3")->result_array();
			if(count($sell)>0)
			 {
				foreach($sell as $kye=>$se)
				 {
					$newarray[$se["PRODUCTID"]]["PRODUCTID"]=$se["PRODUCTID"];
					$newarray[$se["PRODUCTID"]]["ORDERNUM"]=$newarray[$se["PRODUCTID"]]["ORDERNUM"]+$se["ORDERNUM"];
					$newarray[$se["PRODUCTID"]]["PRODUCTNAME"]=$se["PRODUCTNAME"];
				 }
			}
		 }

				$filename = date('YmdHis') . '.csv';
				header("Content-type: text/csv");
				header("content=text/html;charset=utf8");
				header("Content-Disposition: attachment; filename=" . $filename);
				header('Cache-Control: must-revalidate,post-check=0,pre-check=0');
				header('Expires:0');
				header('Pragma:public');
				$str = "商品编号,数量,名称\r\n";
				foreach($newarray as $key=>$v)
				{
					$str .= "" . $v["PRODUCTID"].",".$v["ORDERNUM"].",".$v["PRODUCTNAME"]."\r\n";
				}
		  echo mb_convert_encoding($str, "cp936", "UTF-8");
		  exit();
	}

	public function getsearchscanorder($s, $e, $shopdata)
	{

		/*
[ORDERID] => 63859138161114600732
[SHOPTYPE] => Wish-Samcos
[SHOPTYPEID] => 59
[MONEYASK] => 132.3		//收款金额
[MONEYACTION] => 65		//商品成本
[MONEYEXPRESSASK] => 18.9	//运费收入
[MONEYEXPRESSACTION] =>		//真实运费
[SLRESERVE7] => 97.8275		//物流成本
[PAYPALFEEAMOUNT] =>		//交易费用
[SELLNUM] => 1			//数量
[FINALVALUEFEE] => 22.68	//平台交易费
[QLRESERVE2] => ,17683-GREY-XL,	//sku
[batch_orderweight] => 609.00		//重量
[batch_shipping_name] => 中邮小包挂
[batch_shipping_number] => RH911041751CN
		*/
		 if (count($shopdata) == 0) {
            die('未选中店铺！');
        }
        $startime = $s . " 00:00:00";
        $endtime = $e . " 23:59:59";
        $listdb = array();
        foreach ($shopdata as $shopid) {
			 $sql = "select ORDERID,SHOPTYPE,SHOPTYPEID,MONEYASK,MONEYACTION,MONEYEXPRESSASK,MONEYEXPRESSACTION,SLRESERVE7,PAYPALFEEAMOUNT,SELLNUM,FINALVALUEFEE,QLRESERVE2,CUSTOMERRESERVE2,CUSTOMERCOUNTRY from DB_ORDER where SHOPTYPE = '" . $shopid . "'  AND STATUS = '已完成'  AND to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')>='" . $startime . "' and to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='" . $endtime . "' order by MONEYACTION ASC";
			$query = $this->db2->query($sql);
            $res = $query->result();
            $res = $this->object2array($res);
			
			 if (count($res) > 0) {
				 foreach ($res as $key => $rs){
					$sql = "SELECT * FROM db_mabang_scanorder WHERE batch_order_sn = '" .$rs["ORDERID"]. "' AND opertime>='".$s."' AND opertime <='".$e."' ";
					$rsorder = $this->db1->get_one($sql);
					if($rsorder)
					 {
						 $rs["batch_orderweight"] = $rsorder["batch_orderweight"];
						 $rs["batch_shipping_name"] = $rsorder["batch_shipping_name"];
						 $rs["batch_shipping_number"] = $rsorder["batch_shipping_number"];
						 $listdb[$shopid][$key] = $rs;
					 }
				 }
			 }
			
			

		}
		
		 return $listdb;
		
	
	}

	public function getallscanorderPro()
	{
		$sql = "select ORDERID from DB_SCANORDER where FLAG=1 and OPER = '0003'";
		$query = $this->db2->query($sql);
		$res = $query->result();
		$res = $this->object2array($res);
		foreach($res as $key=>$rs)
		{
			$ct = "马帮订单【{$rs[ORDERID]}】发货减少库存";
			$rsordersan = $this->db1->get_one("SELECT * FROM db_goods_log where content '%".$ct."%'");
			if($rsordersan)
			{
				continue;
			}
			$sell =$this->db2->get_where('DB_SELL',"ORDERID='".trim($rs["ORDERID"])."' and FLAG != 3")->result_array();
			$sellcostprice = 0;
			if(count($sell)>0)
			{
				foreach($sell as $k=>$rgoods)
				{
					$nums = $rgoods['ORDERNUM'];
					$goods_sku = $rgoods['PRODUCTID'];

					if($rgoods['PRODUCTID']=='RUSH SERVICE')	//加急费不计算
					{
						continue;
					}
					if(is_numeric($goods_sku) && preg_match('|^\d{8}$|',$goods_sku))	//数字并且8位SKU并且11 12开头
					{
						$goodscode  = substr($goods_sku,0,2);//取开头2位数
						if($goodscode == '11' || $goodscode =='12')	//是否存在在工厂code
						{
							continue;	//定制衣服按成本价计算
						}
					}
					
					//减库存
					$goods = $this->db1->get_one("SELECT * FROM db_goods where goods_sku='".$goods_sku."'");
					if($goods)
					{
						$rsdb = $this->db1->get_one("select * from db_goods_stock where 1 AND goods_id='".$goods['goods_id']."' AND storage_id=1");
						$sql = "UPDATE db_goods_stock set stock=stock-'".$nums."' where id='".$rsdb["id"]."'";
						$this->db1->query($sql);
						$laststock = $rsdb['stock'] - $nums;
						$content = "修改库存：马帮订单【{$rs[ORDERID]}】发货减少库存[".$nums."] 原来库存[ {$rsdb[stock]} ] 现在库存[ {$laststock} ]";
						$sql = "insert db_goods_log SET goods_id = '".$goods['goods_id']."',updatetime='".date("Y-m-d H:i:s")."',createUid='0',types=1,content='".$content."',createUser='auto',old_data='".$rsdb['stock']."',new_data='".$laststock."'";
						$this->db1->query($sql);
	
					}

				}
			}
			
			

		}
	}
	 /* ************************************
    *	自动获取马帮的扫单发货列表
    *   因为马帮的扫单发货列表会清空数
    **/
	public function getallscanorder()
	{
		$sql = "select * from DB_SCANORDER where FLAG=1";
		$query = $this->db2->query($sql);
		$res = $query->result();
		$res = $this->object2array($res);

		foreach($res as $key=>$rs)
		{
			 $resorder = $this->db1->get_where("db_mabang_scanorder"," batch_order_sn='" .trim($rs["ORDERID"]). "' ")->result_array();
			 if(count($resorder)>=1)
			{
					continue;
			}else{
				 $sql = "SELECT * FROM DB_EXPRESSTYPE WHERE SEQUENCEID = '" . $rs["EXPRESSTYPEID"] . "'";
				 $express = $this->db2->get_one($sql);
				
				$this->db2->select("ORDERID,SHOPTYPE,SHOPTYPEID,MONEYASK,MONEYACTION,MONEYEXPRESSASK,MONEYEXPRESSACTION,SLRESERVE7,PAYPALFEEAMOUNT,SELLNUM,FINALVALUEFEE,QLRESERVE2,CUSTOMERRESERVE2,CUSTOMERCOUNTRY,to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss') as ORDERTIME,CUSTOMERADDRESS");
				$orderdata = $this->db2->get_where('DB_ORDER',"ORDERID='".trim($rs["ORDERID"])."'")->result_array();
				
				if($orderdata[0]["CUSTOMERCOUNTRY"]=='china')
				{
					//如果是中国的，需要对地址做截取
					if($orderdata[0]["CUSTOMERADDRESS"])
					{
						$addresspre = explode(" ",trim($orderdata[0]["CUSTOMERADDRESS"]));
						if($addresspre[0])
						{
							$address = $addresspre[0];
							$rsdbts = $this->CI->fun->get_Estimate_freight($rs["ORDERWEIGHT"],$address,0,$express["NAME"]);
						}
					}

				}else{
					$rsdbts = $this->CI->fun->get_Estimate_freight($rs["ORDERWEIGHT"],$orderdata[0]["CUSTOMERRESERVE2"],0,$express["NAME"]);
				}
				$OPERTIME= date("Y-m-d", strtotime($rs["OPERTIME"]));
				$post="";
				$post["batch_order_sn"] = $rs["ORDERID"];
				$post["mabangorderTime"] = $orderdata[0]["ORDERTIME"];
				$post["batch_shipping_number"] = $rs["EXPRESSID"];
				$post["batch_shipping_name"] = $express["NAME"]?$express["NAME"]:'未填写';
	
				/*
[ORDERID] => 63859138161114600732
[SHOPTYPE] => Wish-Samcos
[SHOPTYPEID] => 59
[MONEYASK] => 132.3		//收款金额
[MONEYACTION] => 65		//商品成本
[MONEYEXPRESSASK] => 18.9	//运费收入
[MONEYEXPRESSACTION] =>		//真实运费
[SLRESERVE7] => 97.8275		//物流成本
[PAYPALFEEAMOUNT] =>		//交易费用
[SELLNUM] => 1			//数量
[FINALVALUEFEE] => 22.68	//平台交易费
[QLRESERVE2] => ,17683-GREY-XL,	//sku
[batch_orderweight] => 609.00		//重量
[batch_shipping_name] => 中邮小包挂
[batch_shipping_number] => RH911041751CN
				*/
				//重新计算当前的商品成本
				$sell =$this->db2->get_where('DB_SELL',"ORDERID='".trim($rs["ORDERID"])."' and FLAG != 3")->result_array();
				$sellcostprice = 0;
				if(count($sell)>0)
				{
					foreach($sell as $k=>$rgoods)
					{
						if($rgoods['PRODUCTID']=='RUSH SERVICE')	//加急费不计算
						{
							continue;
						}
						$sellgoods = $this->db2->get_one("SELECT COSTPRICE FROM DB_PRODUCT WHERE SEQUENCEID='".$rgoods['PRODUCTID']."'");
						if($sellgoods['COSTPRICE']==0)
						{
							//如果抓取到马帮的为0.则通过内部系统计算
							$newCOSTPRICE = $this->CI->fun->get_Goods_costprice($rgoods['PRODUCTID']);
							$sellcostprice = $sellcostprice+($newCOSTPRICE * $rgoods['ORDERNUM']);
							if($newCOSTPRICE>0)
							{
								$this->db2->query("UPDATE DB_PRODUCT SET COSTPRICE='".$newCOSTPRICE."' where SEQUENCEID='".$rgoods['PRODUCTID']."'");
							}
						}else{
							$sellcostprice = $sellcostprice+($sellgoods['COSTPRICE'] * $rgoods['ORDERNUM']);
						}
					}
				}else{
					$sellcostprice = $orderdata[0]["MONEYACTION"];
				}


				//查询平台
				$rsshop = $this->db1->get_one("SELECT * FROM d_shop where name='".$orderdata[0]["SHOPTYPE"]."'");
				if($rsshop)
				{
					$post["yz"] = $rsshop["platfrom"];
				}else{
					$post["yz"] = 0;
				}
				
				$post["SHOPTYPE"] = $orderdata[0]["SHOPTYPE"];
				$post["SHOPTYPEID"] = $orderdata[0]["SHOPTYPEID"];
				
				
				$resSELL = $this->getsellprice(trim($rs["ORDERID"]),"ORDERNUM,SELLPRICE");	//重新从订单销售里面抓取总价
				$sellprice = round($resSELL,2);
				$orderdata[0]["MONEYASK"] = $sellprice;



				$post["MONEYASK"] = $orderdata[0]["MONEYASK"];
				$post["MONEYACTION"] = $sellcostprice;
				$post["MONEYEXPRESSASK"] = $orderdata[0]["MONEYEXPRESSASK"];
				if($orderdata[0]["PAYPALFEEAMOUNT"]){
					$post["PAYPALFEEAMOUNT"] = $orderdata[0]["PAYPALFEEAMOUNT"];
				}else{
					$post["PAYPALFEEAMOUNT"] = ($orderdata[0]["MONEYASK"]+$orderdata[0]["MONEYEXPRESSASK"]) * 0.015;
				}
				$post["SELLNUM"] = $orderdata[0]["SELLNUM"];
				
				if($orderdata[0]["FINALVALUEFEE"] && $rsshop["platfrom"] !=10){
					$post["FINALVALUEFEE"] = $orderdata[0]["FINALVALUEFEE"];
				}else{
					if($rsshop["platfrom"]==2 && $express["NAME"]=='日本邮政')	//如果是亚马逊并且是日本邮政 6%
					{
						$post["FINALVALUEFEE"] = ($orderdata[0]["MONEYASK"]+$orderdata[0]["MONEYEXPRESSASK"]) * 0.1;
					}elseif($rsshop["platfrom"]==6){	//如果是天猫6%
						$post["FINALVALUEFEE"] = ($orderdata[0]["MONEYASK"]+$orderdata[0]["MONEYEXPRESSASK"]) * 0.06;
					}elseif($rsshop["platfrom"]==5){
						$post["FINALVALUEFEE"] = 0;	//如果是淘宝0
					}elseif($rsshop["platfrom"]==10){ //速卖通10%
						$post["FINALVALUEFEE"] = ($orderdata[0]["MONEYASK"]+$orderdata[0]["MONEYEXPRESSASK"]) * 0.1;	
					}else{
						$post["FINALVALUEFEE"] = ($orderdata[0]["MONEYASK"]+$orderdata[0]["MONEYEXPRESSASK"]) * 0.15;
					}
				}
				$post["QLRESERVE2"] = $orderdata[0]["QLRESERVE2"];
				$post["cn_country"] = $orderdata[0]["CUSTOMERRESERVE2"];
				$post["country"] = $orderdata[0]["CUSTOMERCOUNTRY"];
				$post["freight"] = $rsdbts;
				


				if(is_numeric($rsdbts))
				{
					//更新马帮平台预估运费
					$this->db2->query("UPDATE DB_ORDER SET SLRESERVE7='".$rsdbts."' where ORDERID='".$rs["ORDERID"]."'");
				}
				
				//毛利 = 商品收入+运费收入-商品成本-交易费用-平台交易费 - 预估物流

				if(is_numeric($rsdbts))
				{
					$maoli = $orderdata[0]["MONEYASK"]+$orderdata[0]["MONEYEXPRESSASK"] - $sellcostprice-$post["PAYPALFEEAMOUNT"]-$post["FINALVALUEFEE"]-$rsdbts;
					$post["maoli"] = $maoli;

					$allmoney = $orderdata[0]["MONEYASK"]+$orderdata[0]["MONEYEXPRESSASK"];
					if($allmoney>0)
					{
						$post["maolilv"] = round($maoli / ($allmoney),3)*100;
					}else{
						$post["maolilv"] = 0;
					}
				}else{
					$post["maoli"] = 0;
					$post["maolilv"] = 0;
				}
				
				$post["batch_shipping_id"] = $rs["EXPRESSTYPEID"];
				$post["batch_orderweight"] = $rs["ORDERWEIGHT"];
				$post["opertime"] = $OPERTIME;
				$post["oper"] = $rs["OPER"];
				$post["isform"] = 1;
				
				 $rsorderfdsa = $this->db1->get_where("db_mabang_scanorder"," batch_order_sn='" .trim($rs["ORDERID"]). "' ")->result_array();
				 if(count($rsorderfdsa)==0){
					
					 $this->db1->query($this->db1->insert_string('db_mabang_scanorder', $post));
					
					//$this->db1->insert('db_mabang_scanorder',$post);
				 }
				
			}
		}
	}

    /* ************************************
    *	计算当前时间往前数十笔的平均成本
    *
    **/
    function getgoodscost($sku)
    {

    }

    /* ************************************
    *	stdClass Object转array
    *
    **/
    function object2array(&$object)
    {
        $object = json_decode(json_encode($object), true);
        return $object;
    }

    public function getlocationsku($id)
    {
        $sql = "SELECT * FROM p_product WHERE id = '" . $id . "' AND tb = 0";
        $res = $this->db1->get_one($sql);
        return $res;
    }

    public function getmaxid()
    {
        $sql = "SELECT max(to_number(SEQUENCEID)) AS MAXID from DB_PRODUCE_NEW ";
        $query = $this->db2->query($sql);
        $res = $query->result();
        $ts = $res[0]->MAXID + 1;
        return $ts;

    }

    /***************************
     ** 获取sumday里面的，已付款，配货，完成状态下的订单
     ** tbopertime 入库时间
     *********************************/
    public function getsalessum($sku, $sumday, $tbopertime)
    {
        $times = $tbopertime;

        $endtime = date("Y-m-d", strtotime("+$sumday months", strtotime($tbopertime))) . " 23:59:59";
        $startime = $times . " 00:00:00";
		
		$sql="SELECT  sum(A.goods_number) as ORDERNUMLAST  from db_order_sell  A left JOIN db_order_list B on A.order_id = B.order_id where A.goods_sn='".$sku."' AND ( B.order_status=5) and B.ordertime >='".$startime."' and B.ordertime <='".$endtime."'";
		$res = $this->db1->get_one($sql);
		if($res['ORDERNUMLAST'])
		{
			return $res['ORDERNUMLAST'];
		}else{
			return 0;
		}

		/*
        $field = " * ";
        $sql = "SELECT sum(A.ORDERNUM) as ORDERNUMLAST  FROM DB_SELL A left join DB_ORDER B on A.ORDERID = B.ORDERID where A.PRODUCTID='" . $sku . "' AND ($this->status)  AND to_char(B.ORDERTIME,'yyyy-mm-dd hh24:mi:ss')>='" . $startime . "' and to_char(B.ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='" . $endtime . "'";
		  $query = $this->db2->query($sql);
        $res = $query->result();
        if ($res[0]->ORDERNUMLAST) {
            return $res[0]->ORDERNUMLAST;
        }
        return 0;
		*/
		
		

      

    }

    public function getminarray($value)
    {
        $pos = array_search(min($value), $value);
        return $value[$pos];
    }

    /***************************
     ** 查询提成金额
     ** tbopertime 入库时间
     *********************************/
    public function commission($tbopertime, $sku, $costprice, $activityprice)	//按销售数量统计提成
    {

        $allnums = 0;
        $minvalue = array();
        $amount = 0;


        $startime1 = date("Y-m-d", strtotime("+3 months", strtotime($tbopertime)));
        $endtime = $startime1 . " 23:59:59";
        $startime = $tbopertime . " 00:00:00";


        $qsorder = $this->getsaleslastsum($startime, $endtime, $sku);
        foreach ($qsorder as $key => $rs) {
            $allnums = $allnums + $rs->ORDERNUMLAST;
        }


        if ($activityprice > 0) {
            if ($allnums > 0) {
                $amount = $allnums * ($activityprice - $costprice) * 20 / 100;
            }
        }

        return $amount;
    }
	
	/*********************************
	*** 计算马帮某个SKU前十笔订单的平均运费
	***
	*****************/
	public function getsalembyunf($sku,$stime,$endtime,$country)
	{
		$times = date("Y-m-d H:i:s");
		$rsdb = $this->db1->get_one("SELECT * FROM db_mabangsalebonus WHERE sku='".$sku."' AND  DATE_SUB(instime,  INTERVAL 60 DAY) <= '".$times."'");
		if($rsdb)
		{
			return $rsdb["moneyexpressaction"];
		}
		/******如果前面有10笔则提取前面十笔******/
		/*$wheres= "AND B.CUSTOMERCOUNTRY ='".$country."'";
		$sql = "SELECT B.MONEYEXPRESSACTION FROM DB_SELL A left join DB_ORDER B on A.ORDERID = B.ORDERID where A.PRODUCTID='".$sku."' AND B.STATUS ='已完成'  AND to_char(B.ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='" . $stime . "'  $wheres AND B.MONEYEXPRESSACTION >1 AND rownum <=10";
		$query = $this->db2->query($sql);
        $res = $query->result();
		if(count($res)==10)
		{
			foreach($res as $key=>$rs)
			{
				$sumf = $sumf+$rs->MONEYEXPRESSACTION;
			}
			$yunfei = $sumf/count($res);
		
		}else{}*/
		/********如果都没有，提取平均值********/

			$sumf = 0;
			$wheres= "AND B.CUSTOMERCOUNTRY ='".$country."'";
			$sql = "SELECT B.MONEYEXPRESSACTION FROM DB_SELL A left join DB_ORDER B on A.ORDERID = B.ORDERID where A.PRODUCTID='".$sku."' AND B.STATUS ='已完成'  AND to_char(B.ORDERTIME,'yyyy-mm-dd hh24:mi:ss')>='" . $stime . "' and to_char(B.ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='" . $endtime . "'   $wheres AND B.MONEYEXPRESSACTION >1 AND rownum <=10";
			$query = $this->db2->query($sql);
			$res = $query->result();
			if(count($res)==0)
			{
				$yunfei = 0;
			}else{
				if(count($res)>1)
				{
					foreach($res as $key=>$rs)
					{
						$sumf = $sumf+$rs->MONEYEXPRESSACTION;
					}
					$yunfei = $sumf/count($res);
					
				}else{
					$yunfei = 0;
				}
			}
		
		if($yunfei>0){
			$rsdb = $this->db1->get_one("SELECT * FROM db_mabangsalebonus WHERE sku='".$sku."'");
			$postty="";
			$postty["moneyexpressaction"] = $yunfei;
			$postty["sku"] = $sku;
			$postty["ty"] =1;
			$postty["instime"] = date("Y-m-d H:i:s");
			
			if($rsdb)
			{
				$this->db1->update("db_mabangsalebonus",$postty," id='".$rsdb["id"]."'");
			}else{
				$this->db1->insert("db_mabangsalebonus",$postty);
			}
		}
		return $yunfei;
	}
	public function salecommission($tbopertime,$sku,$liquidation,$costprice)	//按销售额统计提成
	{
		//提成=0.1*∑（收款金额+运费收入-商品成本-物流成本-平台交易费-付款交易费）。
		// 如果一个订单的商品数量超过1个，
		$allnums = 0;
		$maolvshouru = 0;
        $minvalue = array();
        $amount = 0;
		$endtime = $liquidation . " 23:59:59";
        $startime = $tbopertime . " 00:00:00";
		$qsorder = $this->getsaleslastsum($startime, $endtime, $sku);
		foreach ($qsorder as $key => $rs) {
            $allnums = $allnums + $rs->ORDERNUMLAST;
			$MONEYEXPRESSACTION = round($rs->MONEYEXPRESSACTIONS,2);
			if($MONEYEXPRESSACTION < 1){	//如果运费为0则计划前十笔运费平均值，并且标注为异常单
					$getyunf = $this->getsalembyunf($sku,$startime,$endtime,$rs->CUSTOMERCOUNTRY);
					$MONEYEXPRESSASKst = $getyunf;	//计算十笔平均值运费
			}else{
					$MONEYEXPRESSASKst = $rs->MONEYEXPRESSACTIONS;//订单中的运费
			}
			if($MONEYEXPRESSASKst>1){
				if($rs->SELLNUMS>1)	//2个以上商品
				{
					$smoney = $rs->AMOUNT;//收款金额
					if($rs->MONEYEXPRESSASK>0)
					{
						$expressask = round($rs->MONEYEXPRESSASK/$rs->SELLNUMS,2) ;	//运费收入
					}else{
						$expressask  = 0;
					}
				    $cosexpress = round($MONEYEXPRESSASKst/$rs->SELLNUMS,2) ;	//运费成本
				}else{
					$smoney = $rs->AMOUNT;	//收款金额
					$expressask  =$rs->MONEYEXPRESSASK;//运费收入
					$cosexpress  =$MONEYEXPRESSASKst;//运费成本
					
				}
				$jiaoyif = $smoney*0.15;
				$fukuanf =  $smoney*0.015;
				$totalcostprice = $totalcostprice + ($costprice*$rs->ORDERNUMLAST);
				$totalsmoney = $totalsmoney+$smoney;
				$totalexpressask = $totalexpressask+$expressask;
				$totalcosexpress = $totalcosexpress+$cosexpress;
				$totaljiaoyif = $totaljiaoyif+$jiaoyif;
				$totalfukuanf = $totalfukuanf+$fukuanf;
			
			}
        }
			$amount =round( ($totalsmoney+$totalexpressask-$totalcostprice-$totalcosexpress-$totaljiaoyif-$totalfukuanf)*0.1,2);
			
			$shuru = $totalsmoney+$totalexpressask;
			
			if($shuru>0){
				$maolvshouru =($amount/0.1)/$shuru* 100;
			}
			//echo $maolvshouru;
			//echo "<br>";
		
		 return array("amount"=>$amount,"maolvshouru"=>$maolvshouru,"totalsmoney"=>$totalsmoney,"totalexpressask"=>$totalexpressask,"totalcostprice"=>$totalcostprice,"totalcosexpress"=>$totalcosexpress,"totaljiaoyif"=>$totaljiaoyif,"totalfukuanf"=>$totalfukuanf);
	}

    /***************************
     ** 查询三个月的清算销售
     ** tbopertime 入库时间
     *********************************/
    public function getsaleslastsum($tbopertime, $endtime, $sku)
    {
		 $sql = "SELECT A.ORDERNUM as ORDERNUMLAST ,A.AMOUNT,A.ORDERNUM,B.MONEYEXPRESSASK,B.ORDERID,B.MONEYASK,B.CUSTOMERTYPE,B.OPERTIME,B.STATUS,B.SELLNUM AS SELLNUMs,B.CUSTOMERCOUNTRY,B.MONEYEXPRESSACTION as MONEYEXPRESSACTIONS,B.ORDERTIME FROM DB_SELL A left join DB_ORDER B on A.ORDERID = B.ORDERID where A.PRODUCTID='" . $sku . "' AND B.STATUS ='已完成'  AND to_char(B.ORDERTIME,'yyyy-mm-dd hh24:mi:ss')>='" . $tbopertime . "' and to_char(B.ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='" . $endtime . "' AND  A.FLAG !=3";
		
        $query = $this->db2->query($sql);
        $res = $query->result();
		
        return $res;

    }


    public function insertdata($id)
    {
        $this->max_id = $this->getmaxid();
        $this->locationsku = $this->getlocationsku($id);


        $sql = "INSERT INTO DB_PRODUCT(SEQUENCEID,SID,CORPID,NAME,STATUS,COSTPRICE,SELLPRICE,STORAGEID,STORAGE,OPER,OPERTIME,CREATEDATE,CATEGORYID,WEIGHT,DECLAREDVALUE)VALUES('" . $this->locationsku["sku"] . "','" . $this->locationsku["sku"] . "',1,'" . $this->locationsku["name"] . "','正常','" . $this->locationsku["costprice"] . "','" . $this->locationsku["price"] . "',22,'亚洲仓','" . $_COOKIE["useraccount"] . "',to_date('" . $this->locationsku["opertime"] . "','YYYY-MM-DD HH24:MI:SS'),to_date('" . date("Y-m-d H:i:s") . "','YYYY-MM-DD HH24:MI:SS'),440,400,60) ";
        $this->db2->query($sql);
        //echo $sql;
        //echo "<br>";


        $sql = "INSERT INTO DB_PRODUCE_NEW(SEQUENCEID,PRODUCTID)VALUES('" . $this->max_id . "','" . $this->locationsku["sku"] . "')";    //更新入库
        $this->db2->query($sql);
        //echo $sql;
        //echo "<br>";

        $dates = date("Ymd", strtotime($this->locationsku["opertime"]));
        $sql = "INSERT INTO DB_PRODUCT_AVG(SKU,QUSHI,DAYS,YYYYMMDD)VALUES('" . $this->locationsku["sku"] . "',1,1,'" . $dates . "')";
        $this->db2->query($sql);
        //echo $sql;
        //echo "<br>";
        //更新数据到马帮系统
        //$res  = $this->updatelocalhostproduct($id);
        return 200;
        //print_r($this->max_id);
        //print_r($this->locationsku);
        //die;
    }
	  /***************************
     ** 更新马帮商品信息
     ** tbopertime 入库时间
     *********************************/
	public function insertMabangProduct($goods_id)
	{
		 $this->max_id = $this->getmaxid();
		 $rsdb = $this->db1->get_one("SELECT * FROM db_product_develop WHERE id='".$goods_id."' AND status=6");
		 if($rsdb)
		 {
			$overtime = date("Y-m-d H:i:s",$rsdb["overtime"]);
			$sql = "INSERT INTO DB_PRODUCT(SEQUENCEID,SID,CORPID,NAME,STATUS,COSTPRICE,SELLPRICE,STORAGEID,STORAGE,OPER,OPERTIME,CREATEDATE,CATEGORYID,WEIGHT,DECLAREDVALUE)VALUES('" . $rsdb["sku"] . "','" . $rsdb["sku"] . "',1,'" . $rsdb["name"] . "','正常','" . $rsdb["samplecosprice"] . "','" . $rsdb["saleprice"] . "',22,'亚洲仓','" . $_COOKIE["useraccount"] . "',to_date('" . $overtime . "','YYYY-MM-DD HH24:MI:SS'),to_date('" . date("Y-m-d H:i:s") . "','YYYY-MM-DD HH24:MI:SS'),440,400,60) ";
			$this->db2->query($sql);

			$sql = "INSERT INTO DB_PRODUCE_NEW(SEQUENCEID,PRODUCTID)VALUES('" . $this->max_id . "','" . $rsdb["sku"] . "')";    //更新入库
			$this->db2->query($sql);
			
			$dates = date("Ymd", $rsdb["overtime"]);
			$sql = "INSERT INTO DB_PRODUCT_AVG(SKU,QUSHI,DAYS,YYYYMMDD)VALUES('" .$rsdb["sku"] . "',1,1,'" . $dates . "')";
			$this->db2->query($sql);
		 }


	}

	/***************************
     ** 新系统扫单入库时，需要更新马帮的商品库存
     **  DB_PRODUCTLOG 日志表
	 **　DB_PRODUCT　　库存表
     *********************************/

	public function changmabangstock($goods_sn,$num,$order)
	{
		$rsdb = $this->db2->get_one("SELECT * FROM DB_PRODUCT WHERE SEQUENCEID='".$goods_sn."'");
		if($rsdb)
		{
			$newstock = $rsdb["SAVENUM"] - $num;
			$this->db2->query("UPDATE DB_PRODUCT SET SAVENUM = $newstock where SEQUENCEID = '".$goods_sn."'");	//更新库存数量
			//$rst = rand(1000,9999);
			//$content = "新系统扫单出货扣除库存,订单:{$order},旧库存:{$rsdb[SAVENUM]},新库存:{$newstock}";
			//$SEQUENCEID = $rsdb["SEQUENCEID"].time().rand(1000,9999);
			//$rsdbsell = $this->db2->get_one("SELECT * FROM DB_PRODUCTLOG WHERE SEQUENCEID='".$SEQUENCEID."' AND SID='".$rsdb["SID"]."' AND CONTENT='".$content."'");
			//if(!$rsdbsell){
				//$sql = "INSERT INTO DB_PRODUCTLOG(SEQUENCEID,SID,NAME,OPER,OPERTIME,CORPID,OPERTYPE,CONTENT)VALUES('" .$SEQUENCEID . "','".$rsdb["SID"]."','" . $goods_sn.$rst.time() . "','007',to_date('" . date("Y-m-d H:i:s") . "','YYYY-MM-DD HH24:MI:SS'),1,3,'".$content."')";
				//$this->db2->query($sql);
			//}
		}
	}
    public function updatelocalhostproduct($sku)
    {
        $sql = "select * from DB_PURCHASEHAND where PRODUCTID='" . $sku . "' AND rownum =1 order by OPERTIME ASC";
        $query = $this->db2->query($sql);
        $res = $query->result();
        $detail = $res[0];

        if ($detail) {

            $tbopertime = date("Y-m-d", strtotime($detail->OPERTIME));
            $liquidation = date("Y-m-d", strtotime("+3 months", strtotime($detail->OPERTIME)));
            $zhixiaotime = date("Y-m-d", strtotime("+6 months", strtotime($detail->OPERTIME)));

            return array("tbopertime" => $tbopertime, "liquidation" => $liquidation, "zhixiaotime" => $zhixiaotime);
        } else {
            return "";
        }

    }

    public function updateshopdata()
    {
        $sql = "select * from DB_SHOP ";
        $res = $this->db2->query($sql);
        $depts = $res->result();
        $deptsname = $this->object2array($depts);
        foreach ($deptsname as $key => $rs) {
			$rsdb = $this->db1->get_one("SELECT * FROM d_shop WHERE name='".$rs["NAME"]."'");
			if($rsdb)
			{
			
			}else{
				$rs["OPERTIME"] = date("Y-m-d", strtotime($rs["OPERTIME"]));
				$sql = "INSERT INTO d_shop (id,name,creattime,creatoper,platfrom,platfromname,openflag)VALUES('" . $rs["SID"] . "','" .trim($rs["NAME"]). "','" . $rs["OPERTIME"] . "','" . $rs["OPER"] . "','" . $rs["RESERVE11"] . "','1','1');";
				$res = $this->db1->query($sql);
				echo $sql;
				echo "<br>";
			}
            //

        }

    }
	
	public function updatecosprice($sku,$price)
	{
		$sql="UPDATE DB_PRODUCT SET COSTPRICE = '".$price."' where SEQUENCEID='".$sku."'";//更新入库
		$this->db2->query($sql);
	}
	public function updatestatus($sku)
	{
		$rsdb = $this->db2->get_one("select * from DB_PRODUCT where SEQUENCEID='".$sku."'");
		if($rsdb["STATUS"] !='停产')
		{
			$sql="UPDATE DB_PRODUCT SET STATUS = '停产' where SEQUENCEID='".$sku."'";//更新入库
			$this->db2->query($sql);
		}
	}
	
    public function getproductlist($page,$num)
    {
		//销售大于等于3的  7952个SKU
		$ts = 500;
        if ($page == 1) {
            $start = 1 * $page;
        } else {
            $start = $ts * ($page - 1) + 1;
        }
        $startime="2016-01-01 00:00:00";
		$endtime = date("Y-m-d"). "23:59:59";
       // $endtime ="2016-12-31 23:59:59";
        $end = $ts * $page;
		if($end>37500)
		{
			echo $num;

			echo "<br>";

			echo $page;
			die;
		}
		 
		
        $sql = "SELECT *  FROM (SELECT a.*, ROWNUM rn  FROM (SELECT * FROM DB_PRODUCT ORDER BY  SEQUENCEID DESC) a)  WHERE rn BETWEEN $start AND $end";
        $query = $this->db2->query($sql);
        $res = $query->result();
		
		
        foreach ($res as $key => $rs) {
            //一年的时间内是否有销售
           //$rsdb = $this->getsaleslastsum($startime,$endtime,$rs->SEQUENCEID);
           //print_r($rsdb);
           $sql = "SELECT sum(A.ORDERNUM) as ORDERNUMLAST  FROM DB_SELL A left join DB_ORDER B on A.ORDERID = B.ORDERID where A.PRODUCTID='" . $rs->SEQUENCEID . "' AND ($this->status)  AND to_char(B.ORDERTIME,'yyyy-mm-dd hh24:mi:ss')>='" . $startime . "' and to_char(B.ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='" . $endtime . "'";
		   $rsdb = $this->db2->get_one($sql);
		   if($rsdb["ORDERNUMLAST"]>=3)
		   {
				
				if (preg_match("/([\x81-\xfe][\x40-\xfe])/",$rs->SEQUENCEID, $match)) {	//包含中文的不保存
					
				}else{
					$goodsno =  $rs->SEQUENCEID;
				
					//判断是否包含-
					$expgoodsno = explode("-",trim($goodsno));
					if(count($expgoodsno)>=2){
						$parent_goods = $expgoodsno[0];
					}else{
						$parent_goods = trim($goodsno);
					}


					

						if($rs->CATEGORYID==441)
						{
							$bigclassID = 1;
							$secondclassID = 6;
							$ThreeclassID = 15;
							$supplier = 3;
						}elseif($rs->CATEGORYID==444)
						{
							$bigclassID = 2;
							$secondclassID =4;
							$ThreeclassID = 0;
							$supplier = 2;
						}elseif($rs->CATEGORYID==443)
						{
							$bigclassID = 2;
							$secondclassID =4;
							$ThreeclassID = 0;
							$supplier = 1;
						}else
						{
							$bigclassID = 1;
							$secondclassID = 6;
							$ThreeclassID = 14;
							$supplier = 3;
						}

						if($rs->STATUS =='正常')
						{
							$status = 2;
						}
						if($rs->STATUS =='重点维护')
						{
							$status = 3;
						}
						if($rs->STATUS =='待开发')
						{
							$status = 8;
						}
						if($rs->STATUS =='清仓')
						{
							$status = 5;
						}
						if($rs->STATUS =='停产')
						{
							$status = 4;
						}
						if($rs->STATUS =='自动创建')
						{
							$status = 7;
						}
						if($rs->STATUS =='暂停销售')
						{
							$status =6;
						}
						if($rs->SELLPRICE==null)
						{
							$rs->SELLPRICE = 0;
						}
						if($rs->LENGTH==null)
						{
							$rs->LENGTH = 0;
						}
						if($rs->WIDTH==null)
						{
							$rs->WIDTH = 0;
						}
						if($rs->HIGH==null)
						{
							$rs->HIGH = 0;
						}

						if(is_numeric($goodsno) && preg_match('|^\d{8}$|',$goodsno))	//数字并且8位
						{
							if(substr($goodsno,0,2)==11)
							{
								$supplier = 1;	//11开头的8位数字 工厂1
							}

							if(substr($goodsno,0,2)==12)
							{
								$supplier = 2; //12开头的8位数字 工厂2
							}
						}else{
							$supplier = 3; //其他都是外采
						}

					

						$postdata="";
						if($rs->OPERTIME){
							$OPERTIME= date("Y-m-d", strtotime($rs->OPERTIME));
						}else{
							$OPERTIME="2016-01-01 23:59:59";
						}
						$postdata['p_parent_sku']	= $parent_goods;
						$postdata['p_parent_name']	= $rs->NAME;
						$postdata['p_en_goods_name']= $rs->NAMEEN;
						$postdata['p_yz']	= 0;
						$postdata['p_bigclassid']	= $bigclassID;
						$postdata['p_secondclassid']= $secondclassID;
						$postdata['p_threeclassid'] = $ThreeclassID;
						$postdata['p_goods_brand'] = null;
						$postdata['p_costprice']	= $rs->COSTPRICE;
						$postdata['p_procurement']  = 15;
						$postdata['p_inventory_day']= 15;
						$postdata['p_weight']		= $rs->WEIGHT;
						$postdata['p_sellprice']	= $rs->SELLPRICE;
						$postdata['p_pd_length']	= $rs->LENGTH;
						$postdata['p_pd_width']		= $rs->WIDTH;
						$postdata['p_pd_height']	= $rs->HIGH;
						$postdata['p_pd_declare_value']= $rs->DECLAREDVALUE;
						$postdata['p_goodstypeID']	= 0;
						$postdata['p_sale_status']  = $status;
						$postdata['p_updatetime']	=$OPERTIME;
						$postdata['p_intime']	=$OPERTIME;
						$postdata['p_createID']	=$_COOKIE["userid"];
						$postdata['p_createUser']=$_COOKIE["username"];
						$postdata['p_supplier']=$supplier;
						$postdata['p_checkman']	= null;
						$postdata['p_buyer']  = null;
						$postdata['standard']	= $rs->ALIAS3;
						$postdata['memo']  = $rs->DESCR;
						$where = array('p_parent_sku' => $parent_goods);
						$rsdbred = $this->db1->get_where('db_goods_parent',$where)->result_array();
						$this->db1->trans_begin();
						if(count($rsdbred)==0)	//没有母商品
						{
							$this->db1->query($this->db1->insert_string('db_goods_parent', $postdata));
							$parentID = $this->db1->insert_id();
						}else{
							//更新母商品
							$this->db1->update('db_goods_parent', $postdata, 'p_parent_id=' . $rsdbred[0]["p_parent_id"]);
							$parentID = $rsdbred[0]["p_parent_id"];
						}
						
						


						

						/*
							$postdata["goods_parentID"] = $parentID;
		$parentList = $this->db->get_where('db_goods_parent','p_parent_id='.$parentID)->result_array();
		$postdata['goods_parent_sku']	= $parentList[0]["p_parent_sku"];
		$postdata['goods_name']	= $this->input->post('goods_name');
		$postdata['g_bigclassid']	= $this->input->post('bigclassID');
		$postdata['g_secondclassid']= $this->input->post('secondclassID');
		$postdata['g_threeclassid'] = $this->input->post('ThreeclassID');
		$postdata['en_goods_name']	= trim($this->input->post('en_goods_name'));
		$postdata['goods_brand']	= trim($this->input->post('goods_brand'));
		$postdata['g_costprice']	= $this->input->post('costprice');
		$postdata['g_procurement']  = $this->input->post('procurement');
		$postdata['g_inventory_day']= $this->input->post('inventory_day');
		$postdata['g_weight']		= $this->input->post('weight');
		$postdata['g_sellprice']	= $this->input->post('sellprice');
		$postdata['g_pd_length']	= $this->input->post('pd_length');
		$postdata['g_pd_width']		= $this->input->post('pd_width');
		$postdata['g_pd_height']	= $this->input->post('pd_height');
		$postdata['g_pd_declare_value']= $this->input->post('pd_declare_value');
		$postdata['g_goodstypeID']	= $this->input->post('goodstypeID');
		$postdata['g_sale_status']  = $this->input->post('sale_status');
		$postdata['g_updatetime']	=date("Y-m-d H:i:s");
		$postdata['g_createID']		=$_COOKIE["userid"];
		$postdata['g_createUser']	=$_COOKIE["username"];
		$postdata['g_checkman']	= $this->input->post('checkman');
		$postdata['g_buyer']  = $this->input->post('buyer');
		$postdata['standard']	= $this->input->post('standard');
		$postdata['g_supplier']  = $this->input->post('supplier');
		$postdata['memo']  = $this->input->post('memo');
						*/
						/*********子商品**********/
						$postdata ="";
						$postdata["goods_parentID"] = $parentID;
						$parentList = $this->db1->get_where('db_goods_parent','p_parent_id='.$parentID)->result_array();
						$postdata['goods_parent_sku']	= $parentList[0]["p_parent_sku"];
						$postdata['goods_name']	= $rs->NAME;
						$postdata['yz']	= 0;
						$postdata['goods_sku']	= $rs->SEQUENCEID;
						$postdata['g_bigclassid']	= $parentList[0]['p_bigclassid'];
						$postdata['g_secondclassid']=$parentList[0]['p_secondclassid'];
						$postdata['g_threeclassid'] =$parentList[0]['p_threeclassid'];
						$postdata['en_goods_name']	= $rs->NAMEEN;
						$postdata['goods_brand']	=null;
						$postdata['g_costprice']	= $rs->COSTPRICE;
						$postdata['g_procurement']  = 15;
						$postdata['g_inventory_day']= 15;
						$postdata['g_weight']		=$rs->WEIGHT;
						$postdata['g_sellprice']	=$rs->SELLPRICE;
						$postdata['g_pd_length']	=  $rs->LENGTH;
						$postdata['g_pd_width']		= $rs->WIDTH;
						$postdata['g_pd_height']	= $rs->HIGH;
						$postdata['g_pd_declare_value']= $rs->DECLAREDVALUE;
						$postdata['g_goodstypeID']	= 0;
						$postdata['g_sale_status']  = $status;
						$postdata['g_updatetime']	=$OPERTIME;
						$postdata['g_checkman']	= '刘艺';
						$postdata['g_buyer']  = '刘艺';
						$postdata['g_createID']		=$_COOKIE["userid"];
						$postdata['g_createUser']	=$_COOKIE["username"];
						$postdata['standard']	=  $rs->ALIAS3;
						$postdata['memo']  =  $rs->DESCR;
						$postdata['g_supplier']=$supplier;
						if($rs->ALIAS1)
						{
							$postdata['cognatelist']= $rs->ALIAS1;
						}
						$where = array('goods_sku' => $rs->SEQUENCEID);
						$rsdb = $this->db1->get_where('db_goods',$where)->result_array();
						if(count($rsdb)==0)	//没有商品
						{
							$this->db1->query($this->db1->insert_string('db_goods', $postdata));
							$goods_id = $this->db1->insert_id();
						}else{
							$this->db1->update('db_goods', $postdata, 'goods_id=' . $rsdb[0]["goods_id"]);
							$goods_id = $rsdb[0]["goods_id"];
						}
						$imgdata = "";
						$imgdata["goods_id"] = $goods_id;
						$imgdata["updatetime"] = date("Y-m-d H:i:s");
						$imgdata["createUid"] = $_COOKIE["userid"];
						$imgdata["types"] = 1;
						$imgdata["content"] = '从马帮导入商品';
						$imgdata["createUser"] = $_COOKIE["username"];
						$this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));


						//更新默认仓库


						$where = array('goods_id' => $goods_id);
						$rsdbstock = $this->db1->get_where('db_goods_stock',$where)->result_array();
						if(!$rsdbstock){
						$imgdata = "";
						$imgdata["goods_id"] = $goods_id;
						$imgdata["storage_name"] = '一号仓';
						$imgdata["storage_id"] = 1;
						$imgdata["stock"] =0;
						$imgdata["in_transit"] = 0;
						$imgdata["positions"] =$rs->LOCATION;
						$this->db1->query($this->db1->insert_string('db_goods_stock', $imgdata));
						}
						/*
						if($rs->PICTURE1)
						{
							$file_path = pathinfo($rs->PICTURE1); 
							$Path1 =dirname(__FILE__)."/../../"; 
							$Path2 ="uploads/product/".date("Ymd");
							$dir = $Path1.$Path2;
							!is_dir($dir) && @mkdir($dir, 0755, true);
							$Path3= "/".$parent_goods."-".time()."-product.".$file_path['extension'];
							$content=file_get_contents($rs->PICTURE1);//下载到内存
							$Path = $Path1.$Path2.$Path3;
							file_put_contents($Path, $content);
							$txtPath = $Path2.$Path3;
							if(count($rsdb)==0)	//没有商品
							{
								$postdata = "";
								$postdata["goods_id"] = $goods_id;
								$postdata["images_type"] =1;
								$postdata["images_url"] = $rs->PICTURE1;
								$postdata["local_url"] = $txtPath;
								$this->db1->query($this->db1->insert_string('db_goods_images', $postdata));
								$goods_id = $this->db1->insert_id();
							}

						}
						if($rs->PICTURE2)
						{
							$file_path = pathinfo($rs->PICTURE2); 
							$Path1 =dirname(__FILE__)."/../../"; 
							$Path2 ="uploads/product/".date("Ymd");
							$dir = $Path1.$Path2;
							!is_dir($dir) && @mkdir($dir, 0755, true);
							$Path3= "/".$parent_goods."-".time()."-product.".$file_path['extension'];
							$content=file_get_contents($rs->PICTURE2);//下载到内存
							$Path = $Path1.$Path2.$Path3;
							file_put_contents($Path, $content);
							$txtPath = $Path2.$Path3;
							if(count($rsdb)==0)	//没有商品
							{
								$postdata = "";
								$postdata["goods_id"] = $goods_id;
								$postdata["images_type"] =1;
								$postdata["images_url"] = $rs->PICTURE2;
								$postdata["local_url"] = $txtPath;
								$this->db1->query($this->db1->insert_string('db_goods_images', $postdata));
								$goods_id = $this->db1->insert_id();
							}

						}
						if($rs->PICTURE3)
						{
							$file_path = pathinfo($rs->PICTURE3); 
							$Path1 =dirname(__FILE__)."/../../"; 
							$Path2 ="uploads/product/".date("Ymd");
							$dir = $Path1.$Path2;
							!is_dir($dir) && @mkdir($dir, 0755, true);
							$Path3= "/".$parent_goods."-".time()."-product.".$file_path['extension'];
							$content=file_get_contents($rs->PICTURE3);//下载到内存
							$Path = $Path1.$Path2.$Path3;
							file_put_contents($Path, $content);
							$txtPath = $Path2.$Path3;
							if(count($rsdb)==0)	//没有商品
							{
								$postdata = "";
								$postdata["goods_id"] = $goods_id;
								$postdata["images_type"] =1;
								$postdata["images_url"] = $rs->PICTURE3;
								$postdata["local_url"] = $txtPath;
								$this->db1->query($this->db1->insert_string('db_goods_images', $postdata));
								$goods_id = $this->db1->insert_id();
							}

						}
						if($rs->PICTURE4)
						{
							$file_path = pathinfo($rs->PICTURE4); 
							$Path1 =dirname(__FILE__)."/../../"; 
							$Path2 ="uploads/product/".date("Ymd");
							$dir = $Path1.$Path2;
							!is_dir($dir) && @mkdir($dir, 0755, true);
							$Path3= "/".$parent_goods."-".time()."-product.".$file_path['extension'];
							$content=file_get_contents($rs->PICTURE4);//下载到内存
							$Path = $Path1.$Path2.$Path3;
							file_put_contents($Path, $content);
							$txtPath = $Path2.$Path3;
							if(count($rsdb)==0)	//没有商品
							{
								$postdata = "";
								$postdata["goods_id"] = $goods_id;
								$postdata["images_type"] =1;
								$postdata["images_url"] = $rs->PICTURE4;
								$postdata["local_url"] = $txtPath;
								$this->db1->query($this->db1->insert_string('db_goods_images', $postdata));
								$goods_id = $this->db1->insert_id();
							}

						}
						*/
					

				

					if ($this->db1->trans_status() === FALSE)
					{
						$this->db1->trans_rollback();
					}
					else
					{
						$this->db1->trans_commit();
					}
					
				}
			   
			    $num= $num+1;
				
		   }

		

        }

		return $num;
		
    }

	//deliver 发货方式，默认为空
	public function savemabangorderlist($orderlist,$orderType=1,$deliver='',$newwuconfig='')
	{
		$orderlist = explode("\n",trim($orderlist));
		
		
		foreach($orderlist as $key=>$orderID)
		{
			$orderID=str_replace("\n","",$orderID);
			$orderID=str_replace("\r","",$orderID);
			$orderID=str_replace("\r\n","",$orderID);
			if($orderType==1){ //顺丰
				$rsdb = $this->db1->get_one("SELECT * FROM db_mabangorder WHERE orderID='".trim($orderID)."' AND orderType = '".$orderType."'");
			}else{ //其他
				$rsdb = $this->db1->get_one("SELECT * FROM db_mabangorder WHERE isexe = 1 AND orderID='".trim($orderID)."'");
				if(count($rsdb)>0){
					continue;
				}else{
					$rsdb = $this->db1->get_one("SELECT * FROM db_mabangorder WHERE isexe != 1 AND orderID='".trim($orderID)."'");
				}
			}
			if($rsdb)
			{
				$thi1orderid = $rsdb["id"];
			}else{
				$thi1orderid = 0;
			}

			//CUSTOMERQQ 英文地区
			$this->db2->select('CUSTOMERNAME, CUSTOMERTYPE, CUSTOMERTEL1,CUSTOMERTEL2,CUSTOMERQQ,CUSTOMERCOUNTRY,CUSTOMERPROVINCE,CUSTOMERCITY,CUSTOMERADDRESS,CUSTOMERZIPCODE,MONEYTYPE,STATUS');
			$orderdata = $this->db2->get_where('DB_ORDER',"ORDERID='".trim($orderID)."'")->result_array();
			$rs = $orderdata[0];
				
				if( $rs["CUSTOMERTEL1"]=='' ||  $rs["CUSTOMERTEL1"] =='null' || $rs["CUSTOMERTEL1"]=='NULL')
				{
					$rs["CUSTOMERTEL1"] = '00000000';
				}

				$postdata["orderType"] = $orderType;
				$postdata["isform"] = 1;
				$postdata["orderID"] = $orderID;
				$postdata["statusst"]=$rs["STATUS"];
				$$rs["CUSTOMERNAME"]=str_replace("‘","'",$rs["CUSTOMERNAME"]);
				$postdata["customerid"] = addslashes($rs["CUSTOMERNAME"]);
				$postdata["customertype"]= $rs["CUSTOMERTYPE"];
				$postdata["customertel1"]= $rs["CUSTOMERTEL1"];
				$postdata["customertel2"]= $rs["CUSTOMERTEL2"];
				if($rs["CUSTOMERQQ"]=="AA")
				{
					$rs["CUSTOMERQQ"] = "US";
				}
				$postdata["customerqq"]= $rs["CUSTOMERQQ"];
				$postdata["customercountry"]= $rs["CUSTOMERCOUNTRY"];
				$postdata["customerprovince"]= $rs["CUSTOMERPROVINCE"];
				$postdata["customercity"]= $rs["CUSTOMERCITY"];
				$postdata["customeraddress"]= addslashes($rs["CUSTOMERADDRESS"]);
				$postdata["customerzipcode"]= $rs["CUSTOMERZIPCODE"];
				$postdata["moneytype"]= $rs["MONEYTYPE"];
				$postdata["wuyconfig"]= $newwuconfig?$newwuconfig:null;
				$postdata["content1"]= $rs["CONTENT"];
				$postdata["intime"]= date("Y-m-d H:i:s");
				$postdata["createUser"]=$_COOKIE["username"];
				if($deliver){
					$postdata['deliver'] = $deliver;
				}
				if( $thi1orderid)
				{
					$postdata["isexe"]= 0;
					$postdata["exememo"]='重复提交订单';
					$this->db1->update('db_mabangorder', $postdata, 'id=' . $thi1orderid);
				}else{
					  $res = $this->db1->query($this->db1->insert_string('db_mabangorder', $postdata));
				}
				
		}

		$postdata = "";
		foreach($orderlist as $key=>$orderID)
		{
			$rsdb = $this->db1->get_one("SELECT * FROM db_mabangsell WHERE orderid='".trim($orderID)."'");
			if($rsdb)
			{
				continue;	
			}
			$sql = "SELECT A.ORDERID, A.PRODUCTID, A.PRODUCTNAME,A.ORDERNUM,A.WEIGHT,B.SAVENUM,A.SHOPTYPE,A.LOCATION,A.TRADEID,A.DESCR2,A.EBAYITEMID FROM DB_SELL A left join DB_PRODUCT B on A.PRODUCTID = B.SEQUENCEID where A.ORDERID='".trim($orderID)."'  AND   A.FLAG !=3";
			$query = $this->db2->query($sql);
			$depts = $query->result();
			 $selldata = $this->object2array($depts);
			foreach($selldata as $rs)
			{
				$postdata["orderid"] = $rs["ORDERID"];
				if($orderType==9)
				{
					$postdata["productid"]= $rs["EBAYITEMID"];
				}else{
					$postdata["productid"]= $rs["PRODUCTID"];
				}
				$postdata["productname"]= $rs["PRODUCTNAME"];
				$postdata["ordernum"]= $rs["ORDERNUM"];
				$postdata["weight"]= $rs["WEIGHT"];
				$postdata["shoptype"]= $rs["SHOPTYPE"];
				$postdata["locationad"]= $rs["LOCATION"];
				$postdata["tradeid"]= $rs["TRADEID"];
				$postdata["descr2"]= $rs["DESCR2"];
				$postdata["stock"]= $rs["SAVENUM"];
				$res = $this->db1->query($this->db1->insert_string('db_mabangsell', $postdata));

			}
			
		}

		return 200;

		

	}
	

	public function updateordersfexpress($orderID,$mailNO,$name,$expID)
	{
		$sql = "UPDATE DB_ORDER SET EXPRESSTYPE = '".$name."',EXPRESSID='".$mailNO."',EXPRESSTYPEID='".$expID."',STATUS='配货中',EXPRESSWEIGHT='1',EXPRESSTIME=to_date('" . date("Y-m-d H:i:s") . "','YYYY-MM-DD HH24:MI:SS') where ORDERID='".trim($orderID)."'";    //更新入库

        $this->db2->query($sql);
		
	}
	
	public function updatemabangproduct()
	{
		$sql = "UPDATE DB_PRODUCT SET CATEGORYID = 440 WHERE CATEGORYID is null";
		$this->db2->query($sql);
		$sql = "UPDATE DB_PRODUCT SET WEIGHT =400 WHERE WEIGHT =0";
		$this->db2->query($sql);
		$sql = "UPDATE DB_PRODUCT SET DECLAREDVALUE = 60 WHERE DECLAREDVALUE =0 or DECLAREDVALUE is NULL";
		$this->db2->query($sql);
	}

	/****从马帮导订单到工厂系统，半小时执行一次***/
	public function autoinsertordertofactory()
	{
		$orderidstr = $_GET["orderid"];

		if($orderidstr){
			$orderidstr = array_unique(array_filter(explode(",",$orderidstr)));
			$orderidstr = implode("','",$orderidstr);
		}else{
			$orderidstr = "";
		}
		if($orderidstr=="")
		{
			die('请输入订单号！');
		}
		$endtime = date("Y-m-d H:i:s");
		$tbopertime = date("Y-m-d H:i:s",strtotime($endtime)-86000*5);	//只计算当前时间的前10个天的订单
		if($orderidstr)
		{
			$sql = "SELECT * FROM DB_ORDER where (STATUS ='已支付' or STATUS ='新订单' or STATUS ='配货中') AND ORDERID in('".$orderidstr."')";
			
		}else{
			$sql = "SELECT * FROM DB_ORDER where (STATUS ='已支付' or STATUS ='新订单') AND to_char(OPERTIME,'yyyy-mm-dd hh24:mi:ss')>='" . $tbopertime . "' and to_char(OPERTIME,'yyyy-mm-dd hh24:mi:ss')<='" . $endtime . "'";
		}
		$query = $this->db2->query($sql);
        $res = $query->result();
		$depts = $this->object2array($res);
		
		$rsdb = $this->db1->get_where("db_factory","code >0")->result_array();
		foreach($rsdb as $key =>$rs)
		{
			$factorycode[] = $rs["code"];	//工厂编号
		}
		foreach($depts as $key=>$rs)
		{
			$this->db2->select('PRODUCTID');
			$rsgoodslist = $this->db2->get_where('DB_SELL',"ORDERID='".trim($rs["ORDERID"])."'")->result_array();
			foreach($rsgoodslist as $s=>$goods)
			{
				$goodsno = $goods["PRODUCTID"];
				if(is_numeric($goodsno) && preg_match('|^\d{8}$|',$goodsno))	//数字并且8位//判断是否是符合导订的要求 //8位SKU并且11 12开头
				{
					$goodscode  = substr($goodsno,0,2);
					if(in_array($goodscode,$factorycode))
					{
						$rsdb = $this->db1->get_one("SELECT * FROM d_fmtask where orderid = '".trim($rs["ORDERID"])."'");
						if(!$rsdb)
						{
							$postdata=array();
							$postdata["orderid"] = trim($rs["ORDERID"]);
							$postdata["createtime"] = date("Y-m-d H:i:s");
							$postdata["finishtime"] = "0000-00-00 00:00:00";
							$postdata["flag"] = 0;
							$postdata["isform"] = 0;
							$postdata["descr"] = null;
							$this->db1->insert('d_fmtask',$postdata);
						}
					}

					
				}
			}
		}
		if($orderidstr)
		{
			$sql = "UPDATE d_fmtask SET flag = 0 where orderid in('".$orderidstr."')";
			$this->db1->query($sql);
			
			//$this->db1->insert('d_fmtask',array("flag"=>0),"orderid in('".$orderidstr."')");
		}
		
		$this->autoinsertfactoryPro($orderidstr);//执行保存的数据

		
	}

	public function autoinsertfactoryPro($orderidstr="")
	{
		/**************
			**  一个订单2个不一样的SKU，生成两个工厂订单　如：7050514473011，107000553
			**  一个订单2个一样的SKU,生成
			** 订单24100083613
			$rsdbfact = $this->db1->get_where("db_factory","code ='".$goodscode."'")->result_array();
		 	$postdata["factoryId"] = $rsdbfact[0]["id"];
		************/
		$err= 0;
		$orderlist = $this->db1->get_where('d_fmtask',"flag = 0 AND isform = 0")->result_array();
	
		foreach($orderlist as $key=>$rs)
		{
			$orderid = trim($rs["orderid"]);
			$orderdata = $this->db2->get_where('DB_ORDER',"ORDERID='".$orderid."'")->result_array();
			$TRADEID = $orderdata[0]["TRADEID"];
			
			
				$ordersell = $this->db2->get_where('DB_SELL',"ORDERID='".$orderid."'")->result_array();
				foreach($ordersell as $k=>$resell)
				{
					if(is_numeric($resell["PRODUCTID"]) && preg_match('|^\d{8}$|',$resell["PRODUCTID"]))	//数字并且8位//判断是否是符合导订的要求 //8位SKU并且11 12开头
					{
					
					}else{
						continue;
					}

					
					//这里不再做判断，遇到同一个订单购买2个以上的相同的SKU 如：235032287019
					/*
					$rsdt = $this->db1->get_one("select A.goods_sku,B.id,B.mabangorderid,backdealid from db_factory_sell A left JOIN db_factory_order B on A.orderId=B.id where B.backdealid='".$orderdata[0]["TRADEID"]."' AND A.goods_sku='".$resell["PRODUCTID"]."'");
					if($rsdt)
					{
						if($orderidstr)
						{
							
						}else{
							continue;
						}
					}*/
					
					$rsdbshop = $this->db1->get_one("SELECT * FROM d_shop WHERE name='".$orderdata[0]["SHOPTYPE"]."'");
					$rsgoods = $this->db1->get_where("db_goods","goods_sku='".$resell["PRODUCTID"]."'")->result_array();
					if(!$rsgoods[0]["goods_id"])	//没有这个SKU，提示错误，请先去提交SKU
					{
						$logerr = "";
						$logerr["orderID"]= $orderdata[0]["ORDERID"];	//工厂订单错误
						$logerr["types"]= '工厂导入订单错误';	//工厂订单错误
						$logerr["errortext"]="订单：".$orderdata[0]["ORDERID"]." 商品编号：".$resell["PRODUCTID"]."不存在！导入工厂系统不成功！请先录入SKU信息！录入之后系统自动处理！";
						$logerr["touser"] = $rsdbshop["updateoper"]?$rsdbshop["updateoper"]:0;
						$logerr["sku"] = trim($resell["PRODUCTID"]);
						$rserr = $this->db1->get_where("db_error_log","orderID='".$orderdata[0]["ORDERID"]."' and types='工厂导入订单错误'")->result_array();
						if($rserr)
						{
							$logerr["isshow"]=0;
							$this->db1->update('db_error_log',$logerr,"id='".$rserr[0]["id"]."'");
						}else{
							$logerr["instime"]=date("Y-m-d H:i:s");
							$this->db1->insert('db_error_log',$logerr);
						}
						$err = 1;
						continue;
					}
					$err  =0;
					$ORDERNUM = $resell["ORDERNUM"];
					$rsdbfactorder = $this->db1->get_where("db_factory","code ='".substr($resell["PRODUCTID"],0,2)."'")->result_array();
					
					for($i=1;$i<=$ORDERNUM;$i++)
					{
						if($ORDERNUM==1){
							$dealid = $orderdata[0]["TRADEID"];
						}else{
						    $dealid = $orderdata[0]["TRADEID"]."-".$i;
						}
						$this->db1->trans_begin();
						$rsdbfact = $this->db1->limit(1,0)->order_by('id','DESC')->select('orderId')->get("db_factory_order")->result_array();
						if($rsdbfact[0]["orderId"]<300000)
						{
							$fact_orderId = 300000;
						}else{
							$fact_orderId = $rsdbfact[0]["orderId"] +1;
						}
						$postdata = "";
						$postdata["orderId"]   = $fact_orderId;	//工厂订单号
						$postdata["orderTime"] = $rs["createtime"];	//下单时间
						$postdata["status"]	   = 1;	//订单状态
						$postdata["customerId"]= $orderdata[0]["CUSTOMERID"];//顾客ID
						$postdata["customerName"]= $orderdata[0]["CUSTOMERNAME"];//顾客姓名
						$postdata["country"]   = $orderdata[0]["CUSTOMERCOUNTRY"];//国家
						$postdata["city"]      = $orderdata[0]["CUSTOMERCITY"];//城市
						$postdata["address"]   = addslashes($orderdata[0]["CUSTOMERADDRESS"]);//地址
						$postdata["tel"]   = $orderdata[0]["CUSTOMERTEL1"];//电话
						$postdata["email"]   = $orderdata[0]["CUSTOMEREMAIL"];//邮箱
						$postdata["postal"]   = $orderdata[0]["CUSTOMERZIPCODE"];//邮编 
						$postdata["shopId"]   = $orderdata[0]["SHOPTYPE"];//店铺
						$postdata["factoryId"]   =  $rsdbfactorder[0]["id"];//工厂编号
						$postdata["platformId"]   = $rsdbshop["platfromname"];//平台
						$postdata["responsible"]   = $rsdbshop["updateoper"]?$rsdbshop["updateoper"]:0;//订单负责人
						$postdata["provice"]   = $orderdata[0]["CUSTOMERPROVINCE"];//省份
						$postdata["spcodeid"]   = 1;//公司外健 ？
						$postdata["updateflag"]   = 0;//没有派单
						$postdata["dealid"]     = $dealid;	//dealid
						$postdata["isform"]     = 0;	//1来源新系统0来源马帮
						$postdata["engCountry"]   = $orderdata[0]["CUSTOMERRESERVE2"];//英文国家
						$postdata["money"]   =  $orderdata[0]["MONEYASK"];	//订单金额
						$postdata["mabangorderid"]   =  $orderdata[0]["ORDERID"];//马帮OrderID
						$postdata["backdealid"]   =  trim($orderdata[0]["TRADEID"]);//交易号
						//$postdata["moneyexpressask"]   = $orderdata[0]["MONEYEXPRESSASK"];//运费收入
						$this->db1->insert('db_factory_order', $postdata);
						$fastOrderid = $this->db1->insert_id();
					
						$selldata="";
						$selldata["orderId"] = $fastOrderid;
						$selldata["goods_sku"] = $resell["PRODUCTID"];	//SKU
						$selldata["skuID"] = $rsgoods[0]["goods_id"];	//SKU
						$selldata["skuName"] = $rsgoods[0]["goods_name"];	//SKU
						$selldata["price"] =0;	//SKU
						$selldata["spcodeid"] =1;	//公司外健
						$selldata["orderNum"] =1;	//数量
						$this->db1->insert('db_factory_sell', $selldata);
						
						/*******生成备注信息，如果超过1个SKU，每个订单备注中写上与哪个订单合发********/
						if($ORDERNUM>1){
							if($i == $ORDERNUM)	//最后一笔更新完成之后，计算需求填写的备注信息
							{
								$rsdbOrder = $this->db1->get_one("SELECT GROUP_CONCAT(orderId) as needorder FROM `db_factory_order` WHERE 1 and backdealid='".trim($orderdata[0]["TRADEID"])."'");//同属于一个交易订单
								if($rsdbOrder)
								{
									$memo = "以下订单一起发货：".$rsdbOrder["needorder"];
									$this->db1->update("db_factory_order",array("descr"=>$memo),"backdealid='".trim($orderdata[0]["TRADEID"])."'");
								}
							}
						}
						/*******生成备注信息，如果超过1个SKU，每个订单备注中写上与哪个订单合发完成********/

						if ($this->db1->trans_status() === FALSE) {
							$this->db1->trans_rollback();
						} else {
							$this->db1->trans_commit();
						}
					}
				}
				
				if($err==1)
				{
					$this->db1->update('d_fmtask',array("descr"=>date("Y-m-d H:i:s")."导入工厂系统失败,SKU不存在"),"orderid='".$orderid."'");//订单处理完成，更新标识
				}else{
					$rserr = $this->db1->get_where("db_error_log","orderID='".$orderid."' and types='工厂导入订单错误'")->result_array();
					if($rserr)
					{
						$this->db1->update('db_error_log',array("isshow"=>1),"id='".$rserr[0]["id"]."'");	//更新错误提示，不再提示
					}
					$this->db1->update('d_fmtask',array("finishtime"=>date("Y-m-d H:i:s"),"flag"=>1,"descr"=>date("Y-m-d H:i:s")."成功导入工厂系统"),"orderid='".$orderid."'");//订单处理完成，更新标识
				}
			
			
		}
		$this->autoInsertErrProudct();//自动处理没有导入到ERP的SKU系统
		echo "OK";
	}


	function autoInsertErrProudct($t=0)
	{
		if($t==1){	//指定需要导入的SKU信息
			$re = explode(",",$str);
			foreach($re as $key=>$rs)
			{
				$res[$key]["sku"] = $rs;
			}
			
		}else{
			$res = $this->db1->get_where('db_error_log',"isshow =0")->result_array();
		}
		foreach($res as $key=>$rs)
		{
			$rsgoods = $this->db1->get_where("db_goods","goods_sku='".trim($rs["sku"])."'")->result_array();
			if(count($rsgoods)==0)
			{
				$resskustr = $this->db1->get_where('fshop.d_product',"productid = '".trim($rs["sku"])."'")->result_array();
				$ressku = $resskustr[0];
				if($ressku =='')
				{
					continue;
				}
				$postdata="";
				$bigclassID = 2;
				$secondclassID =4;
				$ThreeclassID = 0;
				if($ressku["factoryid"] ==12)	//工厂1
				{
					$supplier = 1;
				}elseif($ressku["factoryid"] ==10)
				{
					$supplier = 2;
				}else{
					$supplier = 3;
				}
				
				if($ressku["createdate"]){
					$OPERTIME= $ressku["createdate"];
				}else{
					$OPERTIME="2016-01-01 23:59:59";
				}
				$postdata['p_parent_sku']	= $ressku["productid"];
				$postdata['p_parent_name']	= $ressku["productname"];
				$postdata['p_en_goods_name']= $ressku["productnameen"];
				$postdata['p_yz']	= 0;
				$postdata['p_bigclassid']	= $bigclassID;
				$postdata['p_secondclassid']= $secondclassID;
				$postdata['p_threeclassid'] = $ThreeclassID;
				$postdata['p_goods_brand'] = null;
				$postdata['p_costprice']	= $ressku["factoryprice"]?$ressku["factoryprice"]:0;
				$postdata['p_procurement']  = 15;
				$postdata['p_inventory_day']= 15;
				$postdata['p_weight']		= 0;
				$postdata['p_sellprice']	= $ressku["sellprice"];
				$postdata['p_pd_length']	= 0;
				$postdata['p_pd_width']		= 0;
				$postdata['p_pd_height']	= 0;
				$postdata['p_pd_declare_value']= 60;
				$postdata['p_goodstypeID']	= 0;
				$postdata['p_sale_status'] =$ressku["status"]?$ressku["status"]:1;
				$postdata['p_updatetime']	=$OPERTIME;
				$postdata['p_intime']	=$OPERTIME;
				
				$postdata['p_createID']	=295;
				$postdata['p_createUser']='刘祥';
				$postdata['p_supplier']=$supplier;
				$postdata['p_checkman']	= '刘艺';
				$postdata['p_buyer']  = '刘艺';
				$postdata['standard']	= $ressku["qualityinfo"];
				$postdata['fabricinfo']	= $ressku["fabricinfo"]?$ressku["fabricinfo"]:0;
				$postdata['memo']  = $ressku["remark"];		
				$postdata['wages']  = $ressku["wages"]?$ressku["wages"]:0;	
				$this->db1->trans_begin();
				
				$this->db1->query($this->db1->insert_string('db_goods_parent', $postdata));
				$parentID = $this->db1->insert_id();
				
				/*********子商品**********/
					$postdata ="";
					$postdata["goods_parentID"] = $parentID;
					$parentList = $this->db1->get_where('db_goods_parent','p_parent_id='.$parentID)->result_array();
					$postdata['goods_parent_sku']	= $parentList[0]["p_parent_sku"];
					$postdata['goods_name']	= $ressku["productname"];
					$postdata['yz']	= 0;
					$postdata['goods_sku']	= $ressku["productid"];
					$postdata['g_bigclassid']	= $parentList[0]['p_bigclassid'];
					$postdata['g_secondclassid']=$parentList[0]['p_secondclassid'];
					$postdata['g_threeclassid'] =$parentList[0]['p_threeclassid'];
					$postdata['en_goods_name']	=$ressku["productnameen"];
					$postdata['goods_brand']	=null;
					$postdata['g_costprice']	=$ressku["factoryprice"]?$ressku["factoryprice"]:0;
					$postdata['g_procurement']  = 15;
					$postdata['g_inventory_day']= 15;
					$postdata['g_weight']		=0;
					$postdata['g_sellprice']	=$ressku["sellprice"];
					$postdata['g_pd_length']	= 0;
					$postdata['g_pd_width']		=0;
					$postdata['g_pd_height']	= 0;
					$postdata['g_pd_declare_value']= 60;
					$postdata['g_goodstypeID']	= 0;
					$postdata['g_sale_status']  = $ressku["status"]?$ressku["status"]:1;
					$postdata['g_updatetime']	=$OPERTIME;
					$postdata['g_checkman']	= '刘艺';
					$postdata['g_buyer']  = '刘艺';
					$postdata['g_createID']		=295;
					$postdata['g_createUser']	='刘祥';
					$postdata['standard']	=   $ressku["qualityinfo"];
					$postdata['memo']  = $ressku["remark"];	
					$postdata['g_supplier']=$supplier;
					$postdata['wages']  = $ressku["wages"]? $ressku["wages"]:0;	
					$postdata['fabricinfo']	= $ressku["fabricinfo"];
					$postdata['cognatelist']	= $ressku["childsku"];

					$this->db1->query($this->db1->insert_string('db_goods', $postdata));
					$goods_id = $this->db1->insert_id();
					//更新日志
					$imgdata = "";
					$imgdata["goods_id"] = $goods_id;
					$imgdata["updatetime"] = date("Y-m-d H:i:s");
					$imgdata["createUid"] = 295;
					$imgdata["types"] = 1;
					$imgdata["content"] = '从马帮导入商品';
					$imgdata["createUser"] = '刘祥';
					$this->db1->query($this->db1->insert_string('db_goods_log', $imgdata));
					//更新默认仓库
					$where = array('goods_id' => $goods_id);
					$rsdbstock = $this->db1->get_where('db_goods_stock',$where)->result_array();
					if(!$rsdbstock){
					$imgdata = "";
					$imgdata["goods_id"] = $goods_id;
					$imgdata["storage_name"] = '一号仓';
					$imgdata["storage_id"] = 1;
					$imgdata["stock"] =0;
					$imgdata["in_transit"] = 0;
					$imgdata["positions"] =$rs->LOCATION;
					$this->db1->query($this->db1->insert_string('db_goods_stock', $imgdata));
					}

					if ($this->db1->trans_status() === FALSE)
					{
						$this->db1->trans_rollback();
					}
					else
					{
						$this->db1->trans_commit();
					}
			}
			
		}

	}

	/***********自动更新库存信息**
	**  库存 库位 
	**  当前状态
	***********/
	function updatemabangstock($page)
	{
		$t1 = microtime(true);
		
		$goodsnostr = "";
		$pageSize  =100;
		$sql = "SELECT goods_id,goods_sku FROM  db_goods WHERE 1";
        if ($page != null) {
            $offset = ($page - 1) * $pageSize;
            $limit = " LIMIT $pageSize OFFSET $offset";
        }
		
		$wheresql = $sql . $limit;
        $query = $this->db1->query($wheresql);
		
        $res = $query->result_array();
		if(count($res)==0)
		{
			echo $wheresql;
			echo "执行完成！";
			die;
		}
		
		foreach($res as $key=>$rs)
		{
			 $sql = "select STORAGE , LOCATION, SAVENUM,SEQUENCEID,STATUS,WEIGHT,ALIAS1,ALERTNUM  FROM DB_PRODUCT where SEQUENCEID='".$rs["goods_sku"]."' ";
			
		     $rsdb = $this->db2->get_one($sql);
			 
			 $nums =$snums= $rsdb["SAVENUM"]?$rsdb["SAVENUM"]:0;
			 if($nums<0)
			 {
				$nums = 0;
			 }
			 if($rsdb){
					
				 
				 //存状态
				 $this->db1->update("db_goods",array("cognatelist"=>$rsdb["ALIAS1"]),"goods_id='".$rs["goods_id"]."'");
				 //判断是否有库存信息
				if($rsdb["STORAGE"] == '亚洲仓')	//进三号仓的库位和库存
				{
					//先判断库位是否存在
					$rsgoodspost = $this->db1->get_one("SELECT * from db_goods_stock where positions='".trim($rsdb["LOCATION"])."' AND goods_id='".$rs["goods_id"]."' ");
					if($rsgoodspost)
					{
						//调成三号仓
						$this->db1->update("db_goods_stock",array("storage_id"=>4,"storage_name"=>'三号仓',"stock"=>$nums)," id='".$rsgoodspost['id']."'");
					}else{
						$this->db1->insert("db_goods_stock",array("stock"=>$nums,"positions"=>trim($rsdb["LOCATION"]),"goods_id"=>$rs["goods_id"],"storage_id"=>4,"storage_name"=>'三号仓'));
					}

				}else{
					//进一号仓库位和库存
					 $rsstock = $this->db1->get_one("select * from db_goods_stock where goods_id ='".$rs["goods_id"]."' AND storage_id = 1");
					 if($rsstock)
					 {
						 $this->db1->update("db_goods_stock",array("stock"=>$nums,"positions"=>trim($rsdb["LOCATION"])),"id='".$rsstock["id"]."'");
					 }else{
						 $this->db1->insert("db_goods_stock",array("stock"=>$nums,"positions"=>trim($rsdb["LOCATION"]),"goods_id"=>$rs["goods_id"],"storage_id"=>1,"storage_name"=>'一号仓'));
					 }

					 echo $nums."->".$rs["goods_sku"]."->".$rs["goods_id"]."->".$snums;
					 echo "<br>";

				}
				
			}else{
				 $rsstock = $this->db1->get_one("select * from db_goods_stock where goods_id ='".$rs["goods_id"]."' AND storage_id = 1");
				 if($rsstock)
				 {
					 $this->db1->update("db_goods_stock",array("stock"=>0,"positions"=>""),"id='".$rsstock["id"]."'");
				 }else{
					 $this->db1->insert("db_goods_stock",array("stock"=>0,"positions"=>"","goods_id"=>$rs["goods_id"],"storage_id"=>1,"storage_name"=>'一号仓'));
				 }
				//自动更新进入马帮
				
			}
		}
		
		//$t2 = microtime(true);
		//echo '耗时'.round($t2-$t1,3).'秒<br>';
		return true;
	
	}
	

	public function batchproductimages($page)
	{
		//先处理图片信息
		$rsdb = $this->db1->get_where("db_factory","code >0")->result_array();
		foreach($rsdb as $key =>$rs)
		{
			$factorycode[] = $rs["code"];	//工厂编号
		}

		$goodsnostr = "";
		$pageSize  =10;
		$sql = "SELECT goods_id,goods_sku,goods_parent_sku FROM  db_goods WHERE 1";
        if ($page != null) {
            $offset = ($page - 1) * $pageSize;
            $limit = " LIMIT $pageSize OFFSET $offset";
        }
		
		$wheresql = $sql . $orderbys . $limit;
        $query = $this->CI->db->query($wheresql);
        $list = $query->result_array();
		if(count($list)==0)
		{
			echo $wheresql;
			echo "执行完成！";
			die;
		}
		
		foreach($list as $key=>$rs)
		{
			$goodsku = $rs["goods_sku"];
			if(is_numeric($goodsku) && preg_match('|^\d{8}$|',$goodsku))	//数字并且8位SKU并且11 12开头
			{
				$goodscode  = substr($goodsku,0,2);//取开头2位数
				if(in_array($goodscode,$factorycode))	//是否存在在工厂code
				{
					continue;
				}
			}
			//如果存在图片，则不再更新了
			$rsdbImages = $this->db1->get_one("SELECT * FROM db_goods_images WHERE goods_id = '".$rs["goods_id"]."'");
			if($rsdbImages)
			{
				continue;
			}

			
			 $sql = "select PICTURE1 , PICTURE2, PICTURE3,PICTURE4  FROM DB_PRODUCT where SEQUENCEID='".$rs["goods_sku"]."' ";
		     $rsdb = $this->db2->get_one($sql);
			 if($rsdb)
			 {
				

				if($rsdb["PICTURE1"])
				{
					$rsdbImages = $this->db1->get_one("SELECT * FROM db_goods_images WHERE goods_id = '".$rs["goods_id"]."' AND images_url='".$rsdb["PICTURE1"]."'");
					if($rsdbImages==""){
						$Images = $this->getMabangImages($rsdb["PICTURE1"],$rs["goods_parent_sku"]);
						if($Images){
							$postImages = "";
							$postImages["goods_id"] = $rs["goods_id"];
							$postImages["images_type"]  = 1;
							$postImages["filesize"]  = $Images["filesize"];
							$postImages["images_url"]  = $Images["images_url"];
							$postImages["local_url"]  = $Images["local_url"];
							$postImages["thumb_url"]  =  $Images["thumb_url"];
							$postImages["filename"]  = $Images["filename"];
							$postImages["createUser"]  = $_COOKIE["username"];
							$postImages["instime"]  = time();
							$this->db1->insert('db_goods_images',$postImages);
						}
					}
				}
				if($rsdb["PICTURE2"])
				{
					$rsdbImages = $this->db1->get_one("SELECT * FROM db_goods_images WHERE goods_id = '".$rs["goods_id"]."' AND images_url='".$rsdb["PICTURE2"]."'");
					if($rsdbImages==""){
					$images2 = $this->getMabangImages($rsdb["PICTURE2"],$rs["goods_parent_sku"]);
					if($images2){
						$postImages = "";
						$postImages["goods_id"] = $rs["goods_id"];
						$postImages["images_type"]  = 1;
						$postImages["filesize"]  = $images2["filesize"];
						$postImages["images_url"]  = $images2["images_url"];
						$postImages["local_url"]  = $images2["local_url"];
						$postImages["thumb_url"]  =  $images2["thumb_url"];
						$postImages["filename"]  = $images2["filename"];
						$postImages["createUser"]  = $_COOKIE["username"];
						$postImages["instime"]  = time();
						$this->db1->insert('db_goods_images',$postImages);
					}
					}
				}
				if($rsdb["PICTURE3"])
				{
					$rsdbImages = $this->db1->get_one("SELECT * FROM db_goods_images WHERE goods_id = '".$rs["goods_id"]."' AND images_url='".$rsdb["PICTURE3"]."'");
					if($rsdbImages==""){
					$images3 = $this->getMabangImages($rsdb["PICTURE3"],$rs["goods_parent_sku"]);
					if($images3){
						$postImages = "";
						$postImages["goods_id"] = $rs["goods_id"];
						$postImages["images_type"]  = 1;
						$postImages["filesize"]  = $images3["filesize"];
						$postImages["images_url"]  = $images3["images_url"];
						$postImages["local_url"]  = $images3["local_url"];
						$postImages["thumb_url"]  =  $images3["thumb_url"];
						$postImages["filename"]  = $images3["filename"];
						$postImages["createUser"]  = $_COOKIE["username"];
						$postImages["instime"]  = time();
						$this->db1->insert('db_goods_images',$postImages);
					}
					}
				}
				if($rsdb["PICTURE4"])
				{
					$rsdbImages = $this->db1->get_one("SELECT * FROM db_goods_images WHERE goods_id = '".$rs["goods_id"]."' AND images_url='".$rsdb["PICTURE4"]."'");
					if($rsdbImages==""){
						$images4 = $this->getMabangImages($rsdb["PICTURE4"],$rs["goods_parent_sku"]);
							if($images4){
							$postImages = "";
							$postImages["goods_id"] = $rs["goods_id"];
							$postImages["images_type"]  = 1;
							$postImages["filesize"]  = $images4["filesize"];
							$postImages["images_url"]  = $images4["images_url"];
							$postImages["local_url"]  = $images4["local_url"];
							$postImages["thumb_url"]  =  $images4["thumb_url"];
							$postImages["filename"]  = $images4["filename"];
							$postImages["createUser"]  = $_COOKIE["username"];
							$postImages["instime"]  = time();
							$this->db1->insert('db_goods_images',$postImages);
						}
					}
				}
				
			 
			 }
			 
		}
		
		return $goodsnostr;
	}


	/***********
	***	处理抓取远程图片，马帮或者内部系统抓取图片都使用这个功能
	*** images_url 原远程连接
	*** local_url  抓取后存放图片
	*** thumb_url  缩略图
	**************/
	function getMabangImages($url,$parent_goods='')
	{
		$url=urldecode($url);
		if(strstr($url,"http") == false)
		{
			return false;
		}
		$file_path = pathinfo($url);
		
		

		if($parent_goods =="")
		{
			$parent_goods = $file_path["filename"];
		}
		
		$ch = curl_init(); 
		$timeout = 10; 
		curl_setopt ($ch, CURLOPT_URL, $url); 
		curl_setopt($ch, CURLOPT_HEADER, 1); 
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
		$contents = curl_exec($ch);
		if (preg_match("/404/", $contents)){
			return false;
		}else{
			$extension = explode("?",$file_path['extension']);
			$file_path['extension'] = $extension[0];
			
			//抓取图片
			$Path1 =dirname(__FILE__)."/../../"; 
			$Path2 ="uploads/product/".date("Ymd");	//存储地址
			$dir = $Path1.$Path2;
			!is_dir($dir) && @mkdir($dir, 0755, true);
			$Path3= "/".$parent_goods."-".time()."-product.".$file_path['extension'];
			$content=file_get_contents($url);//下载到内存
			$Path = $Path1.$Path2.$Path3;
			if(file_put_contents($Path, $content)>0)
			{
				$result_str["images_url"]= $url; 
				$result_str["local_url"]= $Path2.$Path3; 
				//存缩略图

				$upload_path_thumbnail = '/uploads/thumbnail/'.date("Ymd")."";
				$dirthumb = dirname(__FILE__) . "/../..".$upload_path_thumbnail;
				!is_dir($dirthumb) && @mkdir($dirthumb, 0755, true);
				if (file_exists($Path)) {
				$imagesst = $file_path["filename"].time().rand(1000,9999);
				$this->CI->load->library('image_lib');
				$configimg['image_library'] = 'gd2';
				$configimg['source_image'] =$Path;
				$configimg['create_thumb'] = TRUE;
				$configimg['maintain_ratio'] = TRUE;
				$configimg['new_image'] =  $dirthumb."/". $imagesst."." . $file_path['extension'];
				$configimg['width']     = $this->CI->config->item('resizeToWidth');
				$configimg['height']   = $this->CI->config->item('resizeToHeight');
				$this->CI->image_lib->initialize($configimg);
				if ( ! $this->CI->image_lib->resize())
				{
					echo $this->CI->image_lib->display_errors();
					echo "->";
					echo $url;
				}else{
					$this->CI->image_lib->clear();
				}
				}
				$filesize = round(filesize($Path)/1024,2)."kb";//文件大小
				$result_str["filesize"] = $filesize;
				$result_str["filename"] = $imagesst;
				if( $upload_path_thumbnail."/". $imagesst."_thumb." .$file_path['extension'])
				{
					$result_str["thumb_url"] = $upload_path_thumbnail."/". $imagesst."_thumb." .$file_path['extension'];
				}else{
					$result_str["thumb_url"] = $url;
				}
			}
			
			return $result_str;
		}
		
	}
	

	public function getordercount($starttime,$endtime)
	{
		if($_COOKIE["department"] ==1)
		{
			
		}else{
			
			$sql = "SELECT * FROM  d_shop WHERE uploadID = '".$_COOKIE['userid']."'";
			$query = $this->db1->query($sql);
			$dates = $query->result_array();
			if(count($dates)>0)
			{
				foreach($dates as $key=>$rs)
				{
					$shopname[] = $rs['name'];
				}
				$whereshop = implode("','",$shopname);
			}


		}

		if ($whereshop) {
			$sql="SELECT SID from DB_SHOP where NAME in ('".$whereshop."')";
			$query = $this->db2->query($sql);
            $res = $query->result();
            $res = $this->object2array($res);
			if(count($res))
			{
				foreach($res as $key=>$rs)
				{
					$shopid[] = $rs['SID'];
				}
				 $shopid=implode("','",$shopid);
				 $where = " SHOPTYPEID in('".$shopid."') AND";
			}else{
				 return null;//有店铺，但马帮里面查找不到
			}
    	}
		
        $startime = $starttime . " 00:00:00";
        $endtime = $endtime . " 23:59:59";
        $listdb = array();
			$sql="select to_char(ORDERTIME,'yyyy-mm-dd') as dates,SUM(MONEYASK) as allmoneyask,SUM(MONEYEXPRESSASK) as expreeask from DB_ORDER where $where (STATUS = '已完成' or STATUS = '已支付' or STATUS = '配货中' or STATUS = '已发货') AND to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')>='" . $startime . "' and to_char(ORDERTIME,'yyyy-mm-dd hh24:mi:ss')<='" . $endtime . "' group by to_char(ORDERTIME,'yyyy-mm-dd') order by to_char(ORDERTIME,'yyyy-mm-dd') DESC ";
            $query = $this->db2->query($sql);
            $res = $query->result();
            $res = $this->object2array($res);
            if (count($res) > 0) {
                foreach ($res as $key => $rs) {
				   $newlist['list'][$key]["orderDate"] = $rs["DATES"];
                   $newlist['list'][$key]["subtotal"] = round($rs['ALLMONEYASK'] + $rs['EXPREEASK']);
                }
               
            }
		return $newlist;
	}


}